package cn.mzy.controller;

import cn.mzy.domain.User;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Package: cn.mzy.controller
 * @ClassName: UserController
 * @Date:2022/11/14 13:06
 * @Description:
 */
@RestController
@RequestMapping("/user")
@RefreshScope // 动态刷新配置注解
public class UserController {

    @Value("${test.name}")
    private String name;

    @GetMapping("/{id}")
    @SentinelResource(value = "user-server"
            , blockHandler = "getUserByIdBlockHandler"
            , blockHandlerClass = DowngradeUtil.class
            , fallback = "getUserByIdFallback"
            , fallbackClass = FuseDowngradeUtil.class
    )
    public User getUserById(@PathVariable("id") Long id) {
        try {
            // 用于让服务慢响应
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new User(id, "张飞", "ddd" + name);
    }

    public User getUserByIdBlockHandler(@PathVariable("id") Long id, BlockException e) {
        e.printStackTrace();
        return new User(-1L, "服务降级触发！", "当前服务流量过大，请稍后重试！");
    }

    public User getUserByIdFallback(@PathVariable("id") Long id, Throwable e) {
        e.printStackTrace();
        return new User(-1L, "熔断服务降级触发！", "服务不可用，请稍后重试！");
    }
}